package com.gzhryc.net_marketing.cloud.micro.api.controllers.v1;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.time.DateFormatUtils;

import com.gzhryc.common.DateTools;
import com.gzhryc.common.NumberTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.net_marketing.cloud.business.dao.db.PayGoodsOrder;
import com.gzhryc.net_marketing.cloud.business.dao.db.PayGoodsOrderLogistics;
import com.gzhryc.net_marketing.cloud.business.services.PayGoodsOrderLogisticsService;
import com.gzhryc.net_marketing.cloud.business.services.PayGoodsOrderService;
import com.gzhryc.net_marketing.cloud.logistics.ELogisticsState;
import com.gzhryc.net_marketing.cloud.logistics.LogisticsCostUtils;
import com.gzhryc.net_marketing.cloud.logistics.LogisticsInfo;
import com.gzhryc.net_marketing.cloud.logistics.LogisticsSearchAPIService;
import com.gzhryc.net_marketing.cloud.logistics.LogisticsSearchAPIServiceFactory;
import com.gzhryc.net_marketing.cloud.micro.api.ClientAPICodeConstants;
import com.gzhryc.net_marketing.cloud.micro.api.MicroConstants;
import com.gzhryc.net_marketing.cloud.micro.api.dto.v1.LogisticsCostListRequest;
import com.gzhryc.net_marketing.cloud.micro.api.dto.v1.LogisticsCostListResponse;
import com.gzhryc.net_marketing.cloud.micro.api.dto.v1.LogisticsInfoRequest;
import com.gzhryc.net_marketing.cloud.micro.api.dto.v1.LogisticsInfoResponse;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.ILogisticsCostConfig;
import com.gzhryc.shared_device.oem.code.BaseConstants;
import com.gzhryc.shared_device.oem.code.member.dao.db.Member;
import com.gzhryc.shared_device.oem.code.member.dao.db.MemberAddress;
import com.gzhryc.shared_device.oem.code.member.services.MemberAddressService;

public class LogisticsController {

    static Logger log = Logger.getLogger(LogisticsController.class);

    @Route(value = { "/v1/order/logistics/cost/list.do" })
    public LogisticsCostListResponse findLogisticsCostList(HttpServletRequest request) {
        LogisticsCostListResponse apiResp = new LogisticsCostListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        LogisticsCostListRequest apiReq = WebUtils.getJsonRequest(request, LogisticsCostListRequest.class);
        Member member = WebUtils.getAttribute(request, MicroConstants.ATTR_LOGIN_MEMBER, Member.class);
        if (apiReq != null && member != null) {
            try {
                MemberAddress memberAddress = null;
                if (apiReq.getBody().getAddressId() != null) {
                    memberAddress = MemberAddressService.self(BaseConstants.JDBC_KEY).getByKeys(member.getId(),apiReq.getBody().getAddressId());
                }
                if (memberAddress == null) {
                    memberAddress = MemberAddressService.self(BaseConstants.JDBC_KEY).getDefByMemberId(member.getId());
                }
                String province = null;
                if (memberAddress != null && StringTools.isNotBlank(memberAddress.getProvince())) {
                    province = memberAddress.getProvince();
                }

                List<ILogisticsCostConfig> logisticsCostConfigList = LogisticsCostUtils.findCostConfig(apiReq.getBody().getSupplierId(), province);
                if (logisticsCostConfigList != null && logisticsCostConfigList.size() > 0) {
                    apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setItems(new ArrayList<>());
                    for (ILogisticsCostConfig costConfig : logisticsCostConfigList) {
                        LogisticsCostListResponse.LogisticsItem item = new LogisticsCostListResponse.LogisticsItem();
                        item.setCompanyId(costConfig.getCompanyId());
                        item.setName(costConfig.getCompanyName());
                        String moneyStr = NumberTools.getMoneyStr(costConfig.getMoney());
                        item.setMoney(moneyStr);
                        if (costConfig.getFreeMinMoney() != null && costConfig.getFreeMinMoney() > 0) {
                            item.setNote("消费" + moneyStr + "元免邮费");
                        }
                        apiResp.getBody().getItems().add(item);
                    }
                } else {
                    log.error("获取供应商物流配置失败，供应商ID：{{0}}，省份：{{1}}", apiReq.getBody().getSupplierId(), province);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return apiResp;
    }

    @Route(value = { "/v1/order/logistics/search.do" })
    public LogisticsInfoResponse getLogisticsInfo(HttpServletRequest request) {
        LogisticsInfoResponse apiResp = new LogisticsInfoResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        LogisticsInfoRequest apiReq = WebUtils.getJsonRequest(request, LogisticsInfoRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getTradeNo())) {
            PayGoodsOrderLogistics logistics = PayGoodsOrderLogisticsService.self().getByTradeNo(apiReq.getBody().getTradeNo());
            if (logistics == null) {
                PayGoodsOrder simpleTeamPayOrder = PayGoodsOrderService.self().getByTradeNo(apiReq.getBody().getTradeNo());
                if (simpleTeamPayOrder != null && StringTools.isNotBlank(simpleTeamPayOrder.getLogisticsTradeNo())) {
                    logistics = new PayGoodsOrderLogistics();
                    logistics.setTradeNo(simpleTeamPayOrder.getTradeNo());
                    logistics.setLogisticsTradeNo(simpleTeamPayOrder.getLogisticsTradeNo());
                    logistics.setLogisticsCompanyId(simpleTeamPayOrder.getLogisticsCompanyId());
                    logistics.setCreateDate(simpleTeamPayOrder.getCreateDate());
                    logistics = PayGoodsOrderLogisticsService.self().add(logistics);
                } else {
                    return apiResp;
                }
            }
            if (logistics != null) {
                apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                apiResp.getBody().setLogisticsTradeNo(logistics.getLogisticsTradeNo());
                apiResp.getBody().setState(logistics.getLogisticsState());
                apiResp.getBody().setStateName(logistics.getLogisticsStateName());
                LogisticsInfo logisticsInfo = null;
                //终结状态就直接输出
                if (ELogisticsState.SignedIn.index().equals(logistics.getLogisticsState())
                        || ELogisticsState.ReturnReceipt.index().equals(logistics.getLogisticsState())) {
                    if (StringTools.isNotBlank(logistics.getLogisticsContent())) {
                        logisticsInfo = JsonTools.fromJson(logistics.getLogisticsContent(), LogisticsInfo.class);
                    }
                } else if (logistics.getLastUpdateDate() == null || DateTools.differenceHour(logistics.getLastUpdateDate(), new Date()) >= 12) {
                    //触发查询
                    LogisticsSearchAPIService searchAPIService = LogisticsSearchAPIServiceFactory.getDefAPIService();
                    if (searchAPIService != null) {
                        if (PayGoodsOrderLogisticsService.self().lockUpdate(logistics.getTradeNo())) {
                            try {
                                logisticsInfo = searchAPIService.search(logistics.getLogisticsTradeNo(), logistics.getLogisticsCompanyId());
                                if (logisticsInfo != null) {
                                    PayGoodsOrderLogisticsService.self().save(logistics.getTradeNo(), logisticsInfo);
                                }
                            } catch (LogicException e) {
                                apiResp.setCode(ClientAPICodeConstants.EXECUTE_ERROR, e.getMessage());
                            } finally {
                                PayGoodsOrderLogisticsService.self().openUpdate(logistics.getTradeNo());
                            }
                        }
                    } else {
                        log.error("未找到物流信息查询服务");
                    }
                }

                if (logisticsInfo != null && logisticsInfo.getTimeItems() != null && logisticsInfo.getTimeItems().size() > 0) {
                    apiResp.getBody().setTimeItems(new ArrayList<>());
                    for (LogisticsInfo.TimeItem timeItem : logisticsInfo.getTimeItems()) {
                        LogisticsInfoResponse.TimeItem item = new LogisticsInfoResponse.TimeItem();
                        String time = DateFormatUtils.format(timeItem.getTime(), "yyyy-MM-dd HH:mm:ss");
                        item.setTime(time);
                        item.setContent(timeItem.getContent());
                        apiResp.getBody().getTimeItems().add(item);
                    }
                }
            } else {
                apiResp.setCode(ClientAPICodeConstants.EXECUTE_ERROR, "未找到订单的物流信息");
            }
        }
        return apiResp;
    }
}
